import os.path
from datetime import datetime

from selenium import webdriver
from selenium.common import NoSuchElementException, TimeoutException
from selenium.webdriver import Keys, ActionChains
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support.wait import WebDriverWait
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.support import expected_conditions as ec

# 对Chrome驱动操作的封装
class ChromeCrawler:
    def __init__(self):
        # 初始化浏览器驱动
        install_path = ChromeDriverManager().install()
        self.__driver = webdriver.Chrome(service = Service(install_path))

    # 连接网址
    def connect(self, url : str):
        self.__driver.get(url)

    # 查找元素并发送内容
    def find_and_send_keys(self, method, selector : str, content : str | Keys):
        try:
            waiter = WebDriverWait(self.__driver, timeout=2)
            waiter.until(ec.visibility_of_element_located((method, selector)))
            ele = self.__driver.find_element(method, selector)
            ele.send_keys(content)
        except TimeoutException:
            print("查找超时")
        except NoSuchElementException:
            print("未查找到指定元素")

    # 查找元素并点击
    def find_and_click(self, method, selector : str):
        try:
            waiter = WebDriverWait(self.__driver, timeout=2)
            waiter.until(ec.visibility_of_element_located((method, selector)))
            ele = self.__driver.find_element(method, selector)
            ele.click()
        except TimeoutException:
            print("查找超时")
        except NoSuchElementException:
            print("未查找到指定元素")

    # 查找元素并获取到内容
    def find_and_text(self, method, selector : str) -> str:
        try:
            waiter = WebDriverWait(self.__driver, timeout = 2)
            waiter.until(ec.visibility_of_element_located((method, selector)))
            ele = self.__driver.find_element(method, selector)
            return ele.text
        except TimeoutException:
            print("查找超时")
        except NoSuchElementException:
            print("未查找到指定元素")

    def find_and_get_attribute_value(self, method, selector : str, key : str) -> str:
        try:
            waiter = WebDriverWait(self.__driver, timeout=2)
            waiter.until(ec.visibility_of_element_located((method, selector)))
            return self.__driver.find_element(method, selector).get_attribute(key)
        except TimeoutException:
            print("查找超时")
        except NoSuchElementException:
            print("未查找到指定元素")

    def find_and_clear(self, method, selector : str):
        try:
            waiter = WebDriverWait(self.__driver, timeout=2)
            waiter.until(ec.visibility_of_element_located((method, selector)))
            return self.__driver.find_element(method, selector).clear()
        except TimeoutException:
            print("查找超时")
        except NoSuchElementException:
            print("未查找到指定元素")

    # 按下回车键
    def press_enter(self):
        ActionChains(self.__driver).key_down(Keys.ENTER).key_up(Keys.UP).perform()

    # 获取当前页面标题
    def get_title(self) -> str:
        return self.__driver.title

    # 获取当前页面标题
    def get_url(self) -> str:
        return self.__driver.current_url

    # 判断是否发生异地跳转
    def is_jumped_to(self, current_url) -> bool:
        current = self.__driver.current_window_handle
        all_window = self.__driver.window_handles

        for win in all_window:
            if current != win:
                self.__driver.switch_to.window(win)

        return self.get_url() != current_url

    # 保存截图
    def save_screenshots(self):
        if not os.path.exists("./screenshots"):
            os.mkdir("./screenshots")

        filename = "screenshots-" + datetime.now().strftime("%Y-%m-%d-%H-%M-%S.%f") + ".png"
        self.__driver.save_screenshot("./screenshots/" + filename)

    def close(self):
        self.__driver.close()

    def has_classname(self, method, selector : str) -> bool:
        ele = self.__driver.find_element(method, selector)
        if not ele:
            return False

        return True

    # 退出浏览器
    def quit(self):
        self.__driver.quit()
